<template>
  <Layout>
    <div
      class="grid p-4 device-detail-page gap-y-4"
      v-if="loaded && device"
      :key="id"
    >
      <Top :device="device" />
      <Bottom :messages="scrapMessages" />
      <Middle :messages="messages" />
    </div>
    <div v-else class="flex items-center justify-center bg-gray-200 h-96">
      <a-spin size="large" />
    </div>
  </Layout>
</template>

<script lang="ts">
import Layout from "@/layout/index.vue";
import Top from "./layouts/device_detail/Top.vue";
import Middle from "./layouts/device_detail/Middle.vue";
import Bottom from "./layouts/device_detail/Bottom.vue";
import { defineComponent, onBeforeMount, provide, ref } from "vue";
import {
  getDevice,
  searchMessage,
  searchScrapMessage,
} from "@/controller/Cloud";
import { useRoute } from "vue-router";
import { isString } from "@/utils/typeGuard";
import { CloudDevice, CloudDeviceMessageSum } from "model";

export default defineComponent({
  name: "DeviceDetailPage",
  components: {
    Layout,
    Top,
    Middle,
    Bottom,
  },
  setup() {
    const loaded = ref<boolean>(false);
    const route = useRoute();
    const device = ref<CloudDevice>();
    const messages = ref<Array<CloudDeviceMessageSum>>([]);
    const scrapMessages = ref<Array<CloudDeviceMessageSum>>([]);

    const load = async () => {
      if (isString(route.params.id)) {
        loaded.value = false;
        device.value = await getDevice(parseInt(route.params.id));
        messages.value = await searchMessage({
          equipmentId: route.params.id,
        });
        scrapMessages.value = await searchScrapMessage({
          equipmentId: route.params.id,
        });
        loaded.value = true;
      }
    };
    const id = ref<number>(0);
    onBeforeMount(async () => {
      load();
    });
    const refresh = async () => {
      await load();
    };
    provide("refresh", refresh);
    return { loaded, device, id, messages, scrapMessages };
  },
});
</script>

<style scoped lang="scss"></style>
